package keke.ai.code.mother.filter;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import keke.ai.code.mother.common.ResultUtils;
import keke.ai.code.mother.enums.SessionEnum;
import keke.ai.code.mother.exception.ErrorCode;
import keke.ai.code.mother.model.auth.MyUserDetail;
import keke.ai.code.mother.util.WriteJson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import java.io.IOException;
import java.util.Objects;

@Slf4j
public class BasicFilter extends BasicAuthenticationFilter {


    public BasicFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) {

        try {
            Object attribute = request.getSession().getAttribute(SessionEnum.LOGIN_USER.getCode());

            if(Objects.isNull( attribute)) {
                WriteJson.writeJson(request, response, ResultUtils.error(ErrorCode.SYSTEM_ERROR.getCode(), ErrorCode.SYSTEM_ERROR.getMessage()));
            }

            MyUserDetail myUserDetail = (MyUserDetail) attribute;

            // 将用户信息放入上下文
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(myUserDetail, null, myUserDetail.getUserAuthorities());
            authentication.setAuthenticated(true);
            SecurityContextHolder.getContext().setAuthentication(authentication);

            chain.doFilter(request, response);
        } catch (Exception e) {
            log.error(e.getMessage());
            WriteJson.writeJson(request, response, ResultUtils.error(ErrorCode.SYSTEM_ERROR.getCode(), ErrorCode.SYSTEM_ERROR.getMessage()));
        }

    }


}
